﻿using Admin.Core.Common.Auth;
using Admin.Core.Common.Output;
using Admin.Core.Model.Admin;
using Admin.Core.Repository.Admin;
using Admin.Core.Repository.Admin.MenuKj;
using Admin.Core.Service.Admin.MenuKj.Input;
using Admin.Core.Service.Admin.MenuKj.Output;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Core.Service.Admin.MenuKj
{
    public class MenuKjService: IMenuKjService
    {
        private readonly IUser _user;
        private readonly IMapper _mapper;
        private readonly IMenuKjRepository _menuKjRepository;
        private readonly IPermissionRepository _permissionRepository;
        public MenuKjService(IUser user, IMapper mapper,
           IMenuKjRepository menuKjRepository,
           IPermissionRepository permissionRepository)
        {
            _user = user;
            _mapper = mapper;
            _menuKjRepository = menuKjRepository;
            _permissionRepository = permissionRepository;
        }
        public async Task<IResponseOutput> AddAsync(MenuKjInput input)
        {
            _menuKjRepository.baseRepository.Where(x => x.UserId.Equals(_user.Id) && x.Permission.Path.Equals(input.Url))
               .Count(out var total);
            if (total > 0)
            {
                return ResponseOutput.NotOk("您已经设置该菜单的快捷方式！");
            }
            var model = await _permissionRepository.Where(x => x.Path == input.Url).Count(out var t).ToOneAsync();
            if (t == 0)
            {
                return ResponseOutput.NotOk("该菜单的url不存在！");
            }
            MenuKjEntity entity = new MenuKjEntity
            {
                PermissionId = model.Id,
                UserId = _user.Id,
                TenantId = _user.TenantId
            };
            entity.TenantId = _user.TenantId;
           
            var id = (await _menuKjRepository.baseRepository.InsertAsync(entity)).Id;

            return ResponseOutput.Result(id > 0);
        }

        public async Task<IResponseOutput> GetMenuKjListAsync()
        {
            var ls = await _menuKjRepository.baseRepository.Select
                  .Where(a => a.UserId == _user.Id )
                  //.Where(a => a.Locations.AsSelect().Any(t => t.TenantId == _user.TenantId && t.IsDeleted==false && t.Enabled == true))
                  //.InnerJoin<XbcLocationEntity>((a, b) => a.Id == b.XbcWarehouseId && b.TenantId == _user.TenantId && b.Enabled ==true && b.IsDeleted == false)
                  .ToListAsync(a => new MenuKjOutput
                  {
                      Id = a.Id,
                      Name = a.Permission.Label,
                      Url = a.Permission.Path
                  });
            return ResponseOutput.Ok(ls);
        }
        public async Task<IResponseOutput> DeleteAsync(long id)
        {
            var result = await _menuKjRepository.DeleteAsync(id);
            return ResponseOutput.Result(result>0);
        }
    }
}
